/*
 * @Description: 利用open, read, write系统调用实现的cp工具
 *
 * @Author: Cifer
 *
 * @Create on: May 2, 2013
 * 
 */
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>

#define BUF_SIZE 1256

void show_usage() {
	printf("Usage: \n");
	printf("\tcp source_file dest_file \n");
	printf("\n");
}

int main(int argc, char *argv[]) {
	if(argc < 2) {
		show_usage();
		return 0;
	}

	int fd = open(argv[1], O_RDONLY);
	if(-1 == fd) {
		printf("error code: %d\n", 1);
		exit(1);
	}

	int new_fd = -1;
	if(argv[2] && strcmp("", argv[2])) {
		new_fd = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
	} else {
		show_usage();
		return 0;
	}

	if(-1 == new_fd) {
		printf("error code: %d\n", 1);
		exit(1);
	}

	char buf[BUF_SIZE] = {0};
	int act_rbytes = 0;

	act_rbytes = read(fd, buf, BUF_SIZE);
	while(act_rbytes && act_rbytes != -1) {
		int act_wbytes = write(new_fd, buf, act_rbytes);
		char *p = buf;
		/* 如果write没有写入预期的字节数, 则反复写入 */
		while(act_wbytes != act_rbytes && act_wbytes != -1) {
			p = p + act_wbytes;
			act_rbytes = act_rbytes - act_wbytes;
			act_wbytes = write(new_fd, p, act_rbytes);
		}
		if(act_wbytes == -1) {
			printf("error code: %d\n", 1);
			exit(1);
		}
		act_rbytes = read(fd, buf, BUF_SIZE);
	}

	close(fd);
	close(new_fd);

	if(act_rbytes == -1) {
		printf("error code: %d\n", 1);
		exit(1);
	}
}
